﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Mvc;
using System.ComponentModel;
using System.Web.Security;
using EIIS.Infrastructure.Service.System.Authority;
using EIIS.Infrastructure.Service.Business;
using EIIS.Infrastructure.Model.System.Authority;
using EIIS.Infrastructure.Model.Business;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;
using EIIS.FrameWork.Cache;

namespace EIIS.Presentation.Controllers
{
    public class HomeController : BaseController
    {
        public IHospUserManager HospUserManager { get; set; }
        public IRoleManager RoleManager { get; set; }
        public IPackageManager PackageManager { get; set; }
        public ICache Cache { get; set; }

        [ViewPage(false)]
        public ActionResult Index()
        {
            return View();
        }

        [ViewPage(false)]
        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return  RedirectToAction("Login");
        }

        [ViewPage(false)]
        public ActionResult Default()
        {
            return View();
        }

        public ActionResult LoadMenu()
        {
            List<MenuGrid> list = GetMenuGrid();
            return Json(list);
        }

        public ActionResult DoLogin()
        {
            MessageInfo msg = new MessageInfo();
            string strLoginName = Request["txtAccount"];
            string strPwd = Request["txtPassword"];
            if (string.IsNullOrEmpty(strLoginName) || string.IsNullOrEmpty(strPwd))
            {
                msg.IsSuccess = false;
                msg.Message = "用户名和(或)密码不能为空，请重新输入";
                return Json(msg);
            }
            else
            {
                strPwd = HospUser.GetPwdMD5(strPwd);
                if (!HospUserManager.ValidateByName(strLoginName, strPwd))
                {
                    msg.IsSuccess = false;
                    msg.Message = "用户名和(或)密码不正确，请重新输入";
                    return Json(msg);
                }
                else
                {
                    HospUser user = HospUserManager.GetUserByName(strLoginName);
                    if (user.State == PersonState.Disabled)
                    {
                        msg.IsSuccess = false;
                        msg.Message = "该用户已被停用，请重新输入";
                        return Json(msg);
                    }
                    else
                    {
                        Session["username"] = user.Name;
                        FormsAuthentication.SetAuthCookie(strLoginName, false);//加入form验证票据    
                        Cache.SetSessionCache("HospUser", user);
                        Cache.RemoveSessionCache("CurrentUser");

                        msg.IsSuccess = true;
                        msg.Message = "/home/Index";
                        return Json(msg);
                    }
                }
            }
        }

        private List<MenuGrid> GetMenuGrid()
        {
            List<MenuGrid> list = new List<MenuGrid>();
            CurrentUser cUser = new CurrentUser();
            if (cUser.MenuPermission != null && cUser.MenuPermission.LongCount() > 0)
            {
                list = cUser.MenuPermission.OrderBy(m => m.Index).ToList().ConvertAll<MenuGrid>(m =>
                 {
                     return new MenuGrid()
                     {
                         _parentId = m.ParentId,
                         code = m.TreeCode,
                         description = m.Description,
                         id = m.Id,
                         index = m.Index,
                         ispage = m.IsPage,
                         lever = m.Level,
                         name = m.Name,
                         url = string.IsNullOrEmpty(m.ControllerName) == true ? string.Empty : MenuNode.GetURL(m.ControllerName, m.ActionName)
                     };
                 });
            }
            return list;
        }

        public ActionResult LoadData()
        {
            IList<V_Package> list = PackageManager.GetAllPackageView();
            //包装数量
            long BaoZ_Count = list.Where(p =>
            {
                string baozsj = p.BaoZSJ;
                if (!string.IsNullOrEmpty(baozsj))
                {
                    baozsj = baozsj.Substring(0, 10);
                }
                return DateTime.Now.ToString("yyyy-MM-dd") == baozsj;
            }).LongCount();
            //灭菌数量
            long MieJ_Count = list.Where(p =>
            {
                string miejsj = p.MieJSJ;
                if (!string.IsNullOrEmpty(miejsj))
                {
                    miejsj = miejsj.Substring(0, 10);
                }
                return DateTime.Now.ToString("yyyy-MM-dd") == miejsj;
            }).LongCount();
            //发放数量
            long FaF_Count = list.Where(p =>
            {
                string fafsj = p.FaFSJ;
                if (!string.IsNullOrEmpty(fafsj))
                {
                    fafsj = fafsj.Substring(0, 10);
                }
                return DateTime.Now.ToString("yyyy-MM-dd") == fafsj;
            }).LongCount();
            //回收数量
            long HuiS_Count = list.Where(p =>
            {
                string huissj = p.HuiSSJ;
                if (!string.IsNullOrEmpty(huissj))
                {
                    huissj = huissj.Substring(0, 10);
                }
                return DateTime.Now.ToString("yyyy-MM-dd") == huissj;
            }).LongCount();

            var KuCList = PackageManager.GetRecordsByPeriodTime("", "", "ZhuangT in (1,2,20,30)");
            var WeiGHList = PackageManager.GetRecordsByPeriodTime("", "", "ZhuangT in (3,40)");

            //库存总量
            long KuC_Count = KuCList.LongCount();
            //为归还总量
            long WeiGH_Count = WeiGHList.LongCount();


            DateTime now = DateTime.Now;
            //过期库存
            long overdueInventoryCount = KuCList.Where(p =>
            {
                return (!string.IsNullOrEmpty(p.ShiXSJ) && now > (DateTime.Parse(p.ShiXSJ).AddDays(1)));
            }).LongCount();
            //过期未归还（病房的）
            long overdueNoReturnCount = WeiGHList.Where(p =>
            {
                return (!string.IsNullOrEmpty(p.ShiXSJ) && now > (DateTime.Parse(p.ShiXSJ).AddDays(1)));
            }).LongCount();
            //预警库存（有效期7天的，提前1天预警）
            long warningInventory7DaysCount = KuCList.Where(p =>
            {
                if (p.YouXQ <= 7 && !string.IsNullOrEmpty(p.ShiXSJ))
                {
                    DateTime ShiXSJ = DateTime.Parse(p.ShiXSJ);
                    TimeSpan ts = ShiXSJ - now;
                    return (ts.Days == 0);
                }
                else return false;
            }).LongCount();
            //预警未归还（病房的）（有效期7天的，提前1天预警）
            long warningNoReturn7DaysCount = WeiGHList.Where(p =>
            {
                if (p.YouXQ <= 7 && !string.IsNullOrEmpty(p.ShiXSJ))
                {
                    DateTime ShiXSJ = DateTime.Parse(p.ShiXSJ);
                    TimeSpan ts = ShiXSJ - now;
                    return (ts.Days == 0);
                }
                else return false;
            }).LongCount();
            //预警库存（有效期大于7天的，提前3天预警）
            long warningInventoryOtherCount = KuCList.Where(p =>
            {
                if (p.YouXQ > 7 && !string.IsNullOrEmpty(p.ShiXSJ))
                {
                    DateTime ShiXSJ = DateTime.Parse(p.ShiXSJ);
                    TimeSpan ts = ShiXSJ - now;
                    return (ts.Days < 3 && ts.Days >= 0);
                }
                else return false;
            }).LongCount();
            //预警未归还（病房的）（有效期大于7天的，提前3天预警）
            long warningNoReturnOtherCount = WeiGHList.Where(p =>
            {
                if (p.YouXQ > 7 && !string.IsNullOrEmpty(p.ShiXSJ))
                {
                    DateTime ShiXSJ = DateTime.Parse(p.ShiXSJ);
                    TimeSpan ts = ShiXSJ - now;
                    return (ts.Days < 3 && ts.Days >= 0);
                }
                else return false;
            }).LongCount();


            return Json(new {
                bz = BaoZ_Count,
                mj = MieJ_Count,
                ff = FaF_Count,
                hs = HuiS_Count,
                kc = KuC_Count,
                wgh = WeiGH_Count,
                ygqkc = overdueInventoryCount,
                ygqwgh = overdueNoReturnCount,
                gqkc1 = warningInventory7DaysCount,
                gqwgh1 = warningNoReturn7DaysCount,
                gqkc3 = warningInventoryOtherCount,
                gqwgh3 = warningNoReturnOtherCount
            });
        }
    }
}
